package com.greate.community.service;

import com.greate.community.entity.DiscussPost;
import com.greate.community.entity.User;
import com.greate.community.entity.UserBehavior;
import com.greate.community.entity.UserTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * AI推荐服务
 * 基于DeepSeek API实现智能推荐
 */
@Service
public class AIRecommendService {
    private static final Logger logger = LoggerFactory.getLogger(AIRecommendService.class);

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private UserBehaviorService userBehaviorService;

    @Autowired
    private UserTagService userTagService;

    @Autowired
    private DiscussPostService discussPostService;

    /**
     * 获取AI推荐结果
     * @param userId 用户ID
     * @param candidatePosts 候选帖子列表
     * @return 推荐分数列表
     */
    public Map<Integer, Double> getAIRecommendations(int userId, List<DiscussPost> candidatePosts) {
        try {
            // 1. 获取用户画像数据
            Map<String, Object> userProfile = buildUserProfile(userId);
            
            // 2. 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("user_profile", userProfile);
            requestBody.put("candidate_posts", buildCandidatePostsData(candidatePosts));
            
            // 3. 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            
            // 4. 发送请求到DeepSeek API
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            Map<String, Object> response = restTemplate.postForObject(apiUrl, request, Map.class);
            
            // 5. 解析响应结果
            return parseAIResponse(response);
            
        } catch (Exception e) {
            logger.error("获取AI推荐结果时出错", e);
            return new HashMap<>();
        }
    }

    /**
     * 构建用户画像数据
     */
    private Map<String, Object> buildUserProfile(int userId) {
        Map<String, Object> profile = new HashMap<>();
        
        // 获取用户标签
        List<UserTag> userTags = userTagService.getHotUserTags(userId, 10);
        List<String> tags = new ArrayList<>();
        if (userTags != null) {
            for (UserTag tag : userTags) {
                tags.add(tag.getTagName());
            }
        }
        profile.put("tags", tags);
        
        // 获取用户行为数据
        List<UserBehavior> behaviors = userBehaviorService.getHotUserBehaviors(userId, 20);
        List<Map<String, Object>> behaviorData = new ArrayList<>();
        if (behaviors != null) {
            for (UserBehavior behavior : behaviors) {
                Map<String, Object> behaviorMap = new HashMap<>();
                behaviorMap.put("type", behavior.getBehaviorType());
                behaviorMap.put("score", behavior.getScore());
                behaviorMap.put("time", behavior.getCreateTime());
                behaviorData.add(behaviorMap);
            }
        }
        profile.put("behaviors", behaviorData);
        
        return profile;
    }

    /**
     * 构建候选帖子数据
     */
    private List<Map<String, Object>> buildCandidatePostsData(List<DiscussPost> posts) {
        List<Map<String, Object>> candidates = new ArrayList<>();
        for (DiscussPost post : posts) {
            Map<String, Object> postData = new HashMap<>();
            postData.put("id", post.getId());
            postData.put("title", post.getTitle());
            postData.put("content", post.getContent());
            postData.put("create_time", post.getCreateTime());
            candidates.add(postData);
        }
        return candidates;
    }

    /**
     * 解析AI响应结果
     */
    private Map<Integer, Double> parseAIResponse(Map<String, Object> response) {
        Map<Integer, Double> recommendations = new HashMap<>();
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> scores = (List<Map<String, Object>>) response.get("scores");
            if (scores != null) {
                for (Map<String, Object> score : scores) {
                    Integer postId = (Integer) score.get("post_id");
                    Double scoreValue = (Double) score.get("score");
                    recommendations.put(postId, scoreValue);
                }
            }
        } catch (Exception e) {
            logger.error("解析AI响应结果时出错", e);
        }
        return recommendations;
    }
} 